package com.gitee.dictionary.converter;

import com.gitee.dictionary.base.BaseDictionaryEnum;
import com.gitee.dictionary.cache.DictionaryEnumCache;
import com.google.common.base.Strings;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

/**
 * @author <a href="mailto:lin-mt@outlook.com">lin-mt</a>
 */
@Converter(autoApply = true)
public class DictionaryEnumConverter<E extends BaseDictionaryEnum> implements AttributeConverter<E, String> {
    
    private final DictionaryEnumCache dictionaryEnumCache;
    
    public DictionaryEnumConverter(DictionaryEnumCache dictionaryEnumCache) {
        this.dictionaryEnumCache = dictionaryEnumCache;
    }
    
    @Override
    public String convertToDatabaseColumn(E baseDictionaryEnum) {
        if (baseDictionaryEnum == null) {
            return null;
        }
        return baseDictionaryEnum.getCode();
    }
    
    @Override
    public E convertToEntityAttribute(String code) {
        if (Strings.isNullOrEmpty(code)) {
            return null;
        }
        //noinspection unchecked
        return (E) this.dictionaryEnumCache.getByCode(code);
    }
}
